package com.cdc.taskhandler;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

public class AsyncTaskActivity1 extends AppCompatActivity {

    private ProgressBar pbar;
    private ImageView ivResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_async_task1);

        ivResult=findViewById(R.id.ivResult);
        pbar=findViewById(R.id.pbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ivResult.setImageBitmap(null);
                MyAsyncTask myAsyncTask=new MyAsyncTask(ivResult,pbar);
                myAsyncTask.execute("https://cdcdec.github.io/images/1024_2.jpg");
                Snackbar.make(view, "下载开始", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();

            }
        });


    }
}

class MyAsyncTask extends AsyncTask<String,Void,Bitmap> {
    private ImageView imageView;
    private ProgressBar pbar;
    public MyAsyncTask(ImageView imageView, ProgressBar pbar) {
        this.imageView = imageView;
        this.pbar = pbar;
    }
    //在子线程中执行
    @Override
    protected Bitmap doInBackground(String... urls) {
        String path=urls[0];
        DownFile downFile=new DownFile(path);
        Bitmap bitmap=downFile.getBitmap();
        return bitmap;
    }
    //开始执行异步任务  在主线程中执行
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if(pbar!=null && pbar.getVisibility()!=View.VISIBLE){
            pbar.setVisibility(View.VISIBLE);
        }
    }
    //异步任务执行完成  在主线程中执行
    @Override
    protected void onPostExecute(Bitmap s) {
        super.onPostExecute(s);
        if(pbar!=null && pbar.getVisibility()!=View.GONE){
            pbar.setVisibility(View.GONE);
            imageView.setImageBitmap(s);
        }
    }

}
